﻿

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RBACProject.Domian;
using RBACProject.Repositories;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
using System.Threading.Tasks;
using System;
using RBACProject.Application.User;
using RBACProject.Application.User.Dto;
using RBACProject.Application;
using RBACProject.Utlity;
using System.Reflection;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using RBACProject.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;

namespace RBACProject.WebApi.Controllers
{
    /// <summary>
    /// 用户服务端api控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]//权限锁
    //[AuthorizationFilterAttribute]//自定义授权过滤器
    public class UserController : ControllerBase
    {
        private readonly IUserService Iuser;
        private readonly IWebHostEnvironment Iweb;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="iuser"></param>
        /// <param name="iweb"></param>
        public UserController(IUserService iuser, IWebHostEnvironment iweb)
        {
            Iuser = iuser;
            Iweb = iweb;
        }

         
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UserRegister(UserModel model)
        {
            return Ok(await Iuser.UserRegister(model));
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto">参数</param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> GetUserLogin(UserLoginDto dto)
        {
            return Ok(await Iuser.GetUserLogin(dto));
        }

        /// <summary>
        /// 获取全部用户信息并分页
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="fullName">姓名</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserInfo(string userName,string fullName, int pageIndex, int pageSize)
        {
            var result = Result.Success;
            int totalCount;
            int pageCount;
            var list = Iuser.GetUserInfo(userName, fullName, pageIndex, pageSize, out totalCount, out pageCount);
            return Ok(new { result, totalCount, pageCount,list});
        }

        /// <summary>
        /// 查询  按主键查
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> UserQueryById(int id)
        {
            var result = Result.Success;
            var data = await Iuser.UserQueryById(id);
            return Ok(new { result,data});
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteUser(int id)
        {
            return Ok(await Iuser.DeleteAsync(id));
        }

        /// <summary>
        /// 文件上传（图片）
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            //创建文件存放路径
            //如：var dir=$"/Files/Imgs/2023/0917/test.jpg"
            var url = $"/Files/Imgs/{DateTime.Now.ToString("yyyy")}/{DateTime.Now.ToString("MMdd")}/";

            // 判断文件是否上传
            if (file == null || file.Length == 0)
            {
                return BadRequest("未上传文件！");
            }
            //允许图片上传的类型(格式) 大小 
            var allowedFormats = new[] { ".jpg", ".jpeg", "png" };
            //获取上传文件的扩展名,转换为小写字母格式
            var fileExtensions = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (!allowedFormats.Contains(fileExtensions))
            {
                return BadRequest("不支持文件格式");
            }
            // 判断文件大小
            var maxSize = 2 * 1024 * 1024; // 允许的最大文件大小为 2MB
            if (file.Length > maxSize)
            {
                return BadRequest("文件大小超过限制");
            }

            //判断当前文件夹路径是否存在，如果不存在，则创建文件存放路径；
            //var dir=$"/Files/Imgs/2023/0917/test.jpg"
            //var dir=$"/Files/Imgs/2023/0917/test2.jpg"
            if (!Directory.Exists($"{Iweb.WebRootPath}/{url}"))
            {
                System.IO.Directory.CreateDirectory($"{Iweb.WebRootPath}{url}");   
            }
            Random random = new Random();
            //修改上传的图片{格式处理}名称 
            var fileName = $"{url}{DateTime.Now.ToString("yyyyMMddHHmmss")}-{random.Next(100, 999)}{Path.GetExtension(file.FileName)}";
            //文件流
            using (FileStream fs = new FileStream($"{Iweb.WebRootPath}{fileName}",FileMode.Create))
            { 
                await file.CopyToAsync(fs);
                fs.Close();
            }
            return Ok(fileName);
        }

        /// <summary>
        /// 批量删除用户信息
        /// </summary>
        /// <param name="ids">编号</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> BatchDelUser(List<int> ids)
        {
            return Ok(await Iuser.BatchDelUser(ids));
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateUser(UserModel model)
        {
            return Ok(await Iuser.UpdateUser(model));
        }


        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="newPassword">新密码</param>
        /// <param name="id">用户id</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> ResetUserPassword(string newPassword, int id)
        {
            return Ok(await Iuser.ResetUserPassword(newPassword, id));
        }
    }
}
